<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">视频上传</h1>
      <p class="page-description">上传您的原始视频，选择目标平台风格，我们将自动为您生成适配的短视频</p>
    </div>

    <el-card shadow="hover" class="content-card">
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="120px"
        :disabled="uploading"
      >
        <el-form-item label="视频标题" prop="title">
          <el-input
            v-model="form.title"
            placeholder="请输入视频标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="视频描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入视频描述（可选）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="目标平台" prop="target_platform">
          <el-select
            v-model="form.target_platform"
            placeholder="请选择目标平台风格"
            style="width: 100%"
          >
            <el-option
              v-for="template in templates"
              :key="template.template_name"
              :label="template.display_name"
              :value="template.template_name"
            >
              <div class="template-option">
                <div class="template-option-name">{{ template.display_name }}</div>
                <div class="template-option-desc">{{ template.description }}</div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="视频文件" prop="video_file">
          <el-upload
            ref="uploadRef"
            class="video-uploader"
            :auto-upload="false"
            :show-file-list="true"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :before-upload="beforeUpload"
            accept="video/*"
            drag
          >
            <div v-if="!form.video_file" class="upload-content">
              <el-icon class="upload-icon"><UploadFilled /></el-icon>
              <div class="upload-text">
                <p>将视频文件拖拽到此处，或<em>点击上传</em></p>
                <p class="upload-tip">支持 MP4、AVI、MOV、MKV、WEBM 格式，最大 5GB</p>
              </div>
            </div>
            <div v-else class="file-info">
              <el-icon><VideoPlay /></el-icon>
              <span>{{ form.video_file.name }}</span>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :loading="uploading"
            :disabled="!canUpload"
            @click="handleSubmit"
            size="large"
          >
            <el-icon v-if="!uploading"><Upload /></el-icon>
            {{ uploading ? '处理中...' : '开始处理' }}
          </el-button>
          <el-button @click="handleReset" :disabled="uploading" size="large">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 上传进度对话框 -->
    <el-dialog
      v-model="showProgressDialog"
      title="视频处理进度"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="progress-content">
        <div class="current-step">
          <el-tag :type="getProgressType(progressData.status)">
            {{ progressData.status_text }}
          </el-tag>
          <span class="step-text">{{ progressData.current_step }}</span>
        </div>

        <el-progress
          :percentage="progressData.progress"
          :status="progressData.status === 'failed' ? 'exception' : 'success'"
          :stroke-width="12"
          class="mt-20"
        />

        <div v-if="progressData.error_message" class="error-message mt-20">
          <el-alert
            :title="progressData.error_message"
            type="error"
            :closable="false"
            show-icon
          />
        </div>

        <div v-if="progressData.estimated_time" class="estimated-time mt-20">
          <el-icon><Timer /></el-icon>
          预计剩余时间：{{ progressData.estimated_time }}
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="progressData.status === 'completed'"
            type="primary"
            @click="viewResult"
          >
            查看结果
          </el-button>
          <el-button
            v-if="progressData.status === 'failed'"
            type="primary"
            @click="retryUpload"
          >
            重新尝试
          </el-button>
          <el-button
            v-if="progressData.status !== 'processing'"
            @click="closeProgressDialog"
          >
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type UploadInstance } from 'element-plus'
import {
  Upload,
  UploadFilled,
  VideoPlay,
  Timer
} from '@element-plus/icons-vue'
import { request } from '@/api'
import type { VideoUploadRequest, VideoUploadResponse, PlatformTemplate } from '@/types'

const router = useRouter()

// 响应式数据
const formRef = ref<FormInstance>()
const uploadRef = ref<UploadInstance>()
const uploading = ref(false)
const showProgressDialog = ref(false)

const form = reactive<VideoUploadRequest & { video_file?: File }>({
  title: '',
  description: '',
  target_platform: '',
  video_file: undefined
})

const templates = ref<PlatformTemplate[]>([])

const progressData = reactive({
  task_id: '',
  status: 'pending',
  status_text: '等待处理',
  progress: 0,
  current_step: '准备上传文件',
  error_message: '',
  estimated_time: ''
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入视频标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  target_platform: [
    { required: true, message: '请选择目标平台', trigger: 'change' }
  ],
  video_file: [
    { required: true, message: '请选择视频文件', trigger: 'change' }
  ]
}

// 计算属性
const canUpload = computed(() => {
  return form.title && form.target_platform && form.video_file && !uploading.value
})

// 方法
const loadTemplates = async () => {
  try {
    templates.value = await request.get('/videos/templates')
  } catch (error) {
    ElMessage.error('加载平台模板失败')
  }
}

const handleFileChange = (file: any) => {
  form.video_file = file.raw
}

const handleFileRemove = () => {
  form.video_file = undefined
}

const beforeUpload = (file: File) => {
  // 检查文件格式
  const allowedTypes = ['video/mp4', 'video/avi', 'video/mov', 'video/x-matroska', 'video/webm']
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('只支持 MP4、AVI、MOV、MKV、WEBM 格式的视频文件')
    return false
  }

  // 检查文件大小（5GB）
  const maxSize = 5 * 1024 * 1024 * 1024
  if (file.size > maxSize) {
    ElMessage.error('视频文件大小不能超过 5GB')
    return false
  }

  return false // 阻止自动上传
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
  } catch {
    return
  }

  uploading.value = true
  showProgressDialog.value = true

  try {
    // 准备表单数据
    const formData = new FormData()
    formData.append('title', form.title)
    if (form.description) {
      formData.append('description', form.description)
    }
    formData.append('target_platform', form.target_platform)
    formData.append('video_file', form.video_file!)

    // 上传文件并创建任务
    const response: VideoUploadResponse = await request.upload(
      '/videos/upload',
      formData,
      (progress) => {
        progressData.status = 'uploading'
        progressData.status_text = '上传中'
        progressData.progress = Math.min(progress, 10)
        progressData.current_step = `上传文件中... ${progress}%`
      }
    )

    // 保存任务ID
    progressData.task_id = response.task_id

    // 模拟处理进度（实际应该通过WebSocket获取）
    await simulateProcessing()

    ElMessage.success('视频上传成功，正在处理中...')

  } catch (error) {
    console.error('Upload failed:', error)
    progressData.status = 'failed'
    progressData.status_text = '上传失败'
    progressData.error_message = error instanceof Error ? error.message : '上传失败，请重试'
  } finally {
    uploading.value = false
  }
}

const simulateProcessing = async () => {
  const steps = [
    { progress: 20, step: '分析视频内容', time: 30 },
    { progress: 40, step: '语音转录处理', time: 60 },
    { progress: 60, step: '智能剪辑决策', time: 45 },
    { progress: 80, step: '生成适配视频', time: 90 },
    { progress: 95, step: '上传输出文件', time: 15 },
    { progress: 100, step: '处理完成', time: 0 }
  ]

  for (const step of steps) {
    await new Promise(resolve => setTimeout(resolve, step.time * 20)) // 模拟处理时间
    progressData.progress = step.progress
    progressData.current_step = step.step
    progressData.status_text = '处理中'
    progressData.estimated_time = steps.filter(s => s.progress > step.progress).length > 0
      ? `${steps.filter(s => s.progress > step.progress).reduce((acc, s) => acc + s.time, 0)}秒`
      : ''
  }

  progressData.status = 'completed'
  progressData.status_text = '处理完成'
  progressData.current_step = '所有处理已完成'
  progressData.estimated_time = ''
}

const handleReset = () => {
  formRef.value?.resetFields()
  form.video_file = undefined
  uploadRef.value?.clearFiles()
}

const viewResult = () => {
  closeProgressDialog()
  router.push(`/tasks/${progressData.task_id}`)
}

const retryUpload = () => {
  closeProgressDialog()
  progressData.status = 'pending'
  progressData.status_text = '等待处理'
  progressData.progress = 0
  progressData.current_step = '准备上传文件'
  progressData.error_message = ''
  progressData.estimated_time = ''
  handleSubmit()
}

const closeProgressDialog = () => {
  showProgressDialog.value = false
  handleReset()
}

const getProgressType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'info',
    uploading: 'warning',
    processing: 'warning',
    completed: 'success',
    failed: 'danger'
  }
  return typeMap[status] || 'info'
}

// 生命周期
onMounted(() => {
  loadTemplates()
})
</script>

<style scoped>
.video-uploader {
  width: 100%;
}

.upload-content {
  text-align: center;
  padding: 40px 20px;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-text p {
  margin: 0;
  line-height: 1.5;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.file-info .el-icon {
  color: #409eff;
}

.template-option {
  line-height: 1.4;
}

.template-option-name {
  font-weight: 500;
  color: #303133;
}

.template-option-desc {
  font-size: 12px;
  color: #909399;
}

.progress-content {
  text-align: center;
}

.current-step {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-bottom: 20px;
}

.step-text {
  color: #606266;
  font-size: 14px;
}

.error-message {
  text-align: left;
}

.estimated-time {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  color: #909399;
  font-size: 14px;
}

.dialog-footer {
  text-align: center;
}
</style>